package vacuum.lgadmin;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.configuration.file.FileConfiguration;

import vacuum.lgadmin.utils.IOUtils;

public class FileManagement
{
	public static void verifyFiles(LGAdmin lga, File thisFile){
		try{
			File config = new File(lga.getDataFolder() + File.separator + "config.yml");
			if(!config.exists()){
				config.getParentFile().mkdirs();
				config.createNewFile();
				IOUtils.download(config, new URL(lga.configURL));
			} else {
				FileConfiguration cfg = lga.getConfig();
				autoupdate(cfg, lga, thisFile);
			}
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}

	private static void autoupdate(FileConfiguration cfg, LGAdmin lga, File thisFile) throws IOException
	{
		String version = IOUtils.download(new URL(cfg.getString("autoupdate.version")));
		lga.log("Update detected; version " + lga.getDescription().getVersion());
		
		if(cfg.getBoolean("autoupdate.update")){
			
			//check version
			if(!version.equals(lga.getDescription().getVersion())){
				lga.log("Autoupdate enabled. Downloading update.");
				
				//update
				IOUtils.download(thisFile, new URL(cfg.getString("autoupdate.jar")));
				IOUtils.download(new File(lga.getDataFolder() + File.separator + "config.yml"), new URL(cfg.getString("autoupdate.config")));
				
				//Reset auto update
				lga.getConfig().set("autoupdate.update", true);
				lga.getConfig().save(lga.getDataFolder() + File.separator + "config.yml");
				
				lga.getServer().broadcast(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, ChatColor.LIGHT_PURPLE + "[LGAdmin] Updated. Reloading plugins.");
				Bukkit.reload();
				return;
			}
		} else {
			lga.log("Check this project's website for a new stable build " + lga.getDescription().getWebsite() + ".");
			lga.log("Find experimental builds at " + cfg.getString("autoupdate.jar") + ".");
		}
	}
}
